package org.chen.web.controller;

import org.apache.commons.io.IOUtils;
import org.chen.common.RespUtils;
import org.chen.model.Article;
import org.chen.model.Tags;
import org.chen.respmsg.RespEnum;
import org.chen.service.ArticleService;
import org.chen.service.TagsService;
import org.chen.vo.RespBean;
import org.chen.vo.RespPageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    ArticleService service;

    @Autowired
    TagsService tagsService;

   private SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");

    @GetMapping("/all")
    public RespBean<RespPageBean> getAllArticle(String keywords,Integer page,Integer count) {
        List<Article> list = service.getAllArticle(keywords,page,count);
        Long articleCount = service.getAllArticleCount(keywords);
        RespPageBean build = RespPageBean.build();
        build.setData(list).setCount(articleCount).setPage(page).setPageSize(count);
        return RespUtils.result(build, RespEnum.SUCCESS);
    }

    //获取当前用户的所有文章
    @GetMapping("/")
    public RespBean<RespPageBean> getUserArticles(String keywords,@RequestParam(defaultValue = "-1") Integer status,@RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "6") Integer count) {
        List<Article> list = service.getUserArticles(keywords,status,page,count);
        Long listCount = service.getUserArticleCount(keywords, status);
        RespPageBean build = RespPageBean.build();
        build.setData(list).setCount(listCount).setPage(page).setPageSize(count);
        return RespUtils.result(build, RespEnum.SUCCESS);
    }

    @GetMapping("/{id}")
    public RespBean<Article> getArticleById(@PathVariable("id")Integer id){
        Article article = service.getArticleById(id);
        return RespUtils.result(article,RespEnum.SUCCESS);
    }

    //添加文章可能直接发表也可能到草稿箱
    @PostMapping("/")
    public RespBean<String> addArticle(String title,String mdContent,String htmlContent,Integer cid,Integer status,Integer[] tid){
        if (service.addArticle(title, mdContent, htmlContent, cid, status,tid)==1){
            return RespUtils.result(RespEnum.INSERT_SUCCESS);
        }
        return RespUtils.result(RespEnum.INSERT_FAIL);
    }

    //草稿箱-》发表是更新操作
    @PutMapping("/")
    public RespBean<String> updateArticle(Integer id,String title,String mdContent,String htmlContent,Integer cid,Integer status,Integer[] tid){
        if (service.updateArticle(id,title, mdContent, htmlContent, cid, status,tid)==1){
            return RespUtils.result(RespEnum.UPDATE_SUCCESS);
        }
        return RespUtils.result(RespEnum.UPDATE_FAIL);
    }


    @PutMapping("/reset/{aid}")
    public RespBean<String> updateArticleStatusById(@PathVariable("aid") Integer aid) {
        if (service.updateArticleStatusById(aid, 1)==1){
            return RespUtils.result(RespEnum.UPDATE_SUCCESS);
        }
        return RespUtils.result(RespEnum.UPDATE_FAIL);
    }

    //批量发表/删除
    @PutMapping("/mdel")
    public RespBean<String> updateArticleStatusByIds(String aids, Integer status) {
        if (StringUtils.isEmpty(aids)){
            return RespUtils.fail("aids不能为空");
        }
        if (service.updateArticleStatusByIds(aids, status)){
            return RespUtils.result(RespEnum.UPDATE_SUCCESS);
        }
        return RespUtils.result(RespEnum.UPDATE_FAIL);
    }

    @GetMapping("/tags")
    public RespBean<List<Tags>> getAllTags(Integer aid){
        List<Tags> tags = tagsService.getArticleTagsByAid(aid);
        return RespUtils.result(tags, RespEnum.SUCCESS);
    }

    @DeleteMapping("/{ids}")
    public RespBean<String> delArticles(@PathVariable("ids") String aids){
        if (service.delArticleByIds(aids)){
            return RespUtils.result(RespEnum.DELETE_SUCCESS);
        }
        return RespUtils.result(RespEnum.DELETE_FAIL);
    }

    @PostMapping("/upload")
    public RespBean<String> uploadFile(HttpServletRequest req, MultipartFile image){
        //获取当天日期做上传文件的目录
        String formatDate = sdf.format(new Date());

        //获得SpringBoot当前项目的路径：System.getProperty("user.dir")
        //上传文件的存放路径
        String path=System.getProperty("user.dir")+"/upload/"+formatDate;


        File realPath=new File(path);
        //判断目录是否存在,不存在就创建目录
        //mac上要手动创建一个upload目录，否则会报(No such file or directory)
        if (!realPath.exists()){
            realPath.mkdir();
        }

        System.out.println("上传文件保存地址："+realPath);

        //上传的文件使用UUID重命名
        String uuid= UUID.randomUUID().toString().replaceAll("-","");

        //上传文件的原文件名
        String originalFilename = image.getOriginalFilename();
        System.out.println(originalFilename);

        //获取上传文件的后缀名
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index + 1);

        //要保存的文件名
        String fileName=uuid+"."+suffix;
        System.out.println(fileName);


        try {
            image.transferTo(new File(realPath +"/"+ fileName));

            //将upload目录配置为nginx的图片地址代理服务器根目录，然后直接通过nignx访问图片
            //            http://upload.img.com:8088/upload/20200806/4682aa4a9bb746febb5e9d87001cc3d4.jpg
            return RespUtils.result("http://upload.img.com:8088/upload/"+formatDate+"/"+ fileName,RespEnum.UPLOAD_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return RespUtils.fail(e.getMessage());
        }
    }

}
